// pages/index/index.js
var Tool = require("../../utils/ztool.js");
var tool = new Tool();
var util = require('../../utils/util.js');
var appInstance = getApp();
Page({
  data: {
    list: [],
    phone: '',
    loadError: false,
    timer: '',//定时器名字
    countDownNum: '60',//倒计时初始值
    //列表为空
    noData: false,

    //当前窗口的高度
    winHeight: 0,

    pageIndex: 1,

    //没有更多数据
    noMoreData: false,

    //筛选参数，可共用
    inputShowed: false,
    inputVal: "",
    date: '',
    enddate: '',

    // 旅行社筛选参数
    //picker
    carConpamyIndex: -1,
    carConpamyArray: [
      {
        id: -1,
        name: '未接单'
      },
      {
        id: 0,
        name: '未结清'
      },
      {
        id: 1,
        name: '已结清'
      },
      {
        id: 3,
        name: '拒绝接单'
      }
    ],

    //司机筛选参数
    //picker
    payStatusIndex: -1,
    payArray: [
      {
        id: -1,
        name: ''
      },
      {
        id: 0,
        name: '未结清'
      },
      {
        id: 1,
        name: '已结清'
      },
      {
        id: 3,
        name: '拒绝接单'
      }
    ],
    //司机筛选参数结束


    //车公司筛选参数
    traAgency: '',
    traAgencyIndex: -1,
    traAgencyArray: [],

    traStatusIndex: -1,
    traStatusArray: [
      {
        id: 0,
        name: '未确认'
      },
      {
        id: 1,
        name: '已确认'
      },
      {
        id: 3,
        name: '已取消'
      }
    ],
    //车公司筛选参数结束


    //筛选参数结束

    firstLogin: false,
    isLogin: false,
    loginError: false,

    located: false,
    backtag: 0,

    // 会议参数
    meetinglist: [],
    havemeet: false,
    notloadmeeting: false,

    //用车方选取订单分类
    usercarordertype: [
      { name: 'BAOCHE', value: '包车订单', checked: 'true' },
      { name: 'BANCHE', value: '班车订单' },
    ],

    //二维码订单判断
    isQROrder: 0,
    QROrderIDD: '',
    QROrderRoute: ''
  },

  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function () {
    console.log("hide");
    this.setData({
      inputShowed: false
    });
  },
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    });
    console.log(this.data.inputVal)
  },
  clearDate: function () {
    var time1 = util.formatTime1(new Date());
    this.setData({
      date: time1,
      // enddate: time1,
    });
  },
  clearEndDate: function () {
    // var time1 = util.formatTime1(new Date());
    this.setData({
      // date: '2018-01-01',
      enddate: '',
    });
  },

  clearPayStatus: function () {
    this.setData({
      payStatusIndex: -1
    });
  },
  callPhone: function (e) {
    console.log(e)
    if (e.currentTarget.id == "") {
      wx.showToast({
        title: '号码为空',
        icon: 'none',
      });
      return;
    }
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.id //仅为示例，并非真实的电话号码
    });
  },

  getlogincode: function (username) {
    var that = this
    var userTel = username
    wx.login({
      success: function (res) {
        var code = res.code
        console.log(code, userTel)
        that.SetUTelByCodeHdl(code, userTel)
      }
    })
  },



  SetUTelByCodeHdl: function (code, userTel) {
    wx.request({
      url: 'https://www.lanshuicar.com/Server/Weixin/SetUTelByCodeHdl.ashx',
      data: {
        code: code,
        tel: userTel
      },
      method: 'GET',
      success: function (res) {
        var code = res.data.code;
        console.log(res);
        if (code == 0) {
          console.log('post绑定请求成功')
        } else {
          console.log(res)
        }
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function () {
      }
    })
  },

  onLoad: function (options) {
    var that = this;
    console.log('执行了onload')
    //绑定请求
    var username = wx.getStorageSync('username');
    that.getlogincode(username)

    //更新小程序尝试
    if (wx.getUpdateManager) {
      console.log('执行了这一步')
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        console.log(res.hasUpdate)
      })
      updateManager.onUpdateReady(function () {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启蓝水平台？',
          success: function (res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate()
            }
          }
        })
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用新功能，请升级到最新微信版本后重试。'
      })
    }

    var idd = options.idd
    console.log(idd)
    that.data.QROrderIDD = wx.getStorageSync('QROrderIDD')
    that.data.isQROrder = wx.getStorageSync('isQROrder')
    that.data.QROrderRoute = wx.getStorageSync('QROrderRoute')

    console.log(that.data.QROrderIDD)
    console.log(that.data.isQROrder)
    console.log(that.data.QROrderRoute)

    that.setData({
      QROrderIDD: that.data.QROrderIDD,
      isQROrder: that.data.isQROrder,
      QROrderRoute: that.data.QROrderRoute
    });

    wx.setStorageSync('QROrderIDD', '')
    wx.setStorageSync('isQROrder', '0')
    wx.setStorageSync('QROrderRoute', '')

    if (idd) {
      gopush(idd)
    } else {
      console.log('没有idd不跳转到detail')
    }

    var IDD = wx.getStorageSync('IDD')
    if (IDD != '') {
      console.log('有' + IDD)
      gopush(IDD)
      wx.setStorageSync('IDD', '')
    } else {
      console.log('没有' + IDD)
    }
    // 页面初始化 options为页面跳转所带来的参数
    //取出存储的phone 在页面的onShow方法调用时，再取出一次，比较两次的phone时候一直，不一直就重新加载
    this.data.phone = wx.getStorageSync('username');



    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winHeight: res.windowHeight
        });
      }
    });

    // var appInstance = getApp();
    login(this, appInstance);

    // doUpLoadLocation(this);
    getlocate(this);
  },

  getopenid: function () {
    var that = this
    wx.login({
      success: function (res) {
        console.log(res)
        if (res.code) {
          console.log(res.code)
          //https://open.weixin.qq.com/connect/oauth2/authorize
          wx.request({
            url: 'https://api.weixin.qq.com/sns/jscode2session?',
            data: {
              appid: 'wx03ad674e50b8dade',
              secret: 'fb6713e65358ffe4f57ee174a369a98d',
              js_code: res.code,
              grant_type: 'authorization_code'
            },
            method: 'GET',
            success: function (res) {
              console.log(res.data)
              console.log('##')
              // that.sendtest1(res, formId);
            },
            fail: function () {
              console.log(res)

            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },

  sendtest1: function (formId) {
    // sendtest1: function (res, formId) {
    var that = this
    // var openid = res.data.openid
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/token',
      data: {
        appid: 'wx03ad674e50b8dade',
        secret: '1b6f68eb39b47901a17e2b136e251759',
        grant_type: 'client_credential'
      },
      method: 'GET',
      success: function (res) {
        console.log(res)
        that.sendtest2(res, formId);
      },
      fail: function () {

      }
    })
  },

  sendtest2: function (res, formId) {
    console.log(res)
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + res.data.access_token,
      data: {
        touser: 'o44YK0Zg8dZCUnZT_54YItg06aMM',
        template_id: '68Ad1QWX07ijtRZZ5KGYn0HPrN6dMju5-3xBwKUtA8Q',
        form_id: formId,
        data: {
          "keyword1": {
            "value": "339208499",
            "color": "#173177"
          },
          "keyword2": {
            "value": "2015年01月05日 12:30",
            "color": "#173177"
          },
          "keyword3": {
            "value": "粤海喜来登酒店",
            "color": "#173177"
          }
        },
      },
      method: 'POST',
      success: function (res) {
        console.log(res)
      },
      fail: function () {

      }
    })
  },

  onReady: function () {
    // 页面渲染完成
  },

  onShow: function () {
    //获取当前位置
    // getlocate(this)
    // wx.navigateTo({
    //   url: '../jumppage/jumppage',
    // })

    // getlogincode(this)
    console.log('执行了onshow')

    console.log(this.data.backtag);


    if (appInstance.globalData.hasLogin == false && appInstance.globalData.hasLogout == true) {
      // this.data.firstLogin  = true
      this.setData({
        firstLogin: true,
      })
    }

    console.log(appInstance.globalData.firstlogin)
    //重新登录登陆将backtag置为1
    if (appInstance.globalData.firstlogin == true) {
      this.data.backtag = 1
      this.data.pageIndex = 1
      appInstance.globalData.firstlogin = false
    }
    //backtag为1的时候重新加载列表
    if (this.data.backtag == 0) {
      return
    } else {

      this.setData({
        meetinglist: [],
      })

      this.data.backtag = 0
      console.log(this.data.backtag)
    }
    // 页面显示
    // var appInstance = getApp();
    console.log(appInstance);
    console.log(appInstance.globalData.hasLogin)
    this.loadlist()
  },

  // wx.showToast({
  //   title: '正在加载...',
  //   icon: 'loading',
  //   duration: 10000
  // })

  loadlist: function () {
    // wx.showToast({
    //   title: '正在加载',
    //   icon:'loading',
    //   duration:8000
    // })
    if (appInstance.globalData.hasLogin) {
      // this.setData({
      //   firstLogin: false,
      //   isLogin: false,
      //   loginError: false
      // });
      //在数据重置之前判断，首次登录是否为true
      // this.data.firstLogin = true
      if (this.data.firstLogin) {
        this.setData({
          list: []
        });
        var time1 = util.formatTime1(new Date());
        this.setData({
          date: time1
        });
        loadListData(this, 1);
        console.log('已登录，且为首次登陆')
      } else {
        console.log('已登录，不为首次登陆')
        console.log(2222222222222)
        var phone2 = wx.getStorageSync('username');
        this.setData({
          list: [],
        })
        var time1 = util.formatTime1(new Date());
        this.setData({
          date: time1,
        })
        if (phone2 != this.data.phone) {

          //将保存的phone重新赋值为此时本地所保存的phone
          this.data.phone = phone2;
          this.setData({
            list: []
          });

        }
        loadListData(this, 1);
      }
      this.setData({
        firstLogin: false,
        isLogin: false,
        loginError: false
      });


    } else {
      console.log(11111111111)
      var time1 = util.formatTime1(new Date());
      this.setData({
        date: time1
      });
      loadListData(this, 1);
      if (appInstance.globalData.hasLogout) {
        this.setData({
          firstLogin: true,
          isLogin: false,
          loginError: false
        });
      }
    }

    var userType1 = wx.getStorageSync('userType');
    this.setData({
      userType: userType1
    });

    if (this.data.userType == 1 || this.data.userType == 2 || this.data.userType == 3 || this.data.userType == 4) {
      // 调用函数时，传入new Date()参数，返回值是日期和时间  
      var time1 = util.formatTime1(new Date());
      this.setData({
        date: time1
      });
      console.log(this.data.date)
    }

  },

  loadListWhenLoginSuccess() {
    var phone2 = wx.getStorageSync('username');
    if (phone2 != this.data.phone) {
      //将保存的phone重新赋值为此时本地所保存的phone
      this.data.phone = phone2;

      this.setData({
        list: []
      });

      loadListData(this, 1);
    }
  },
  onHide: function () {
  },
  onUnload: function () {
    // this.data.backtag = 2
     //console.log('onunload')
    // console.log(this.data.backtag)
    // 页面关闭
  },

  ballClickEvent: function () {
    console.log('ball', 'click');
  },

  bindRetry: function () {
    loadListData(this, 1);
  },

  //下拉加载
  onPullDownRefresh: function () {
    // var appInstance = getApp();
    console.log(appInstance.globalData.hasLogin)
    if (!appInstance.globalData.hasLogin) return;
    loadListData(this, 1);

    //下拉动作完成之后，将index置为1，没有更多数据字段变为false
    this.data.pageIndex = 1;
    this.data.noMoreData = false;
  },

  //上拉加载
  onReachBottom: function () {
    // var appInstance = getApp();
    console.log(appInstance.globalData.hasLogin)
    if (!appInstance.globalData.hasLogin) return;
    console.log(this.data.noMoreData)
    console.log(this.data.pageIndex)
    if (!this.data.noMoreData) {
      this.data.pageIndex++;
      loadListData(this, this.data.pageIndex);
      var userType1 = wx.getStorageSync('userType');
      if (userType1 == 3) {
        this.data.notloadmeeting = true
      }
    };
  },

  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    });
    console.log(this.data.date)
  },

  bindEndDateChange: function (e) {
    this.setData({
      enddate: e.detail.value
    });
    console.log(this.data.enddate)
  },

  bindPickerChange: function (e) {
    this.setData({
      payStatusIndex: e.detail.value
    })
  },

  doSearch: function () {
    this.data.pageIndex = 1
    this.setData({
      inputShowed: false
    });
    loadListData(this, 1);
  },

  // clearAllParam: function () {
  //   this.setData({
  //     inputShowed: false,
  //     date: '',
  //     enddate: '',
  //     inputVal: '',
  //     payStatusIndex: -1,
  //     traAgency: '',
  //     traAgencyIndex: -1,
  //     traStatusIndex: -1
  //   });

  //   loadListData(this, 1);
  // },

  clearAllParam: function () {
    var time1 = util.formatTime1(new Date());

    this.setData({
      inputShowed: false,
      date: time1,
      enddate: '',
      inputVal: '',
      payStatusIndex: -1,
      traAgency: '',
      traAgencyIndex: -1,
      traStatusIndex: -1
    });

    // loadListData(this, 1);
  },

  goLogin() {
    wx.navigateTo({
      url: '../login/login',
    });
  },

  bindTraStatusPicker: function (e) {
    this.setData({
      traStatusIndex: e.detail.value
    });
  },

  bindTraAgencyPicker: function (e) {
    console.log(e)
    this.setData({
      traAgencyIndex: e.detail.value
    });
  },

  clearTraAgency: function () {
    this.setData({
      traAgencyIndex: -1
    });
  },

  clearTraAgency: function () {
    this.setData({
      traAgencyIndex: -1
    });
  },

  clearTraStatus: function () {
    this.setData({
      traStatusIndex: -1
    });
  },


  addtravelOrder: function () {
    wx.navigateTo({
      url: '../travelAgency/travelOrderAdd/travelOrderAdd',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  addCgsOrder: function () {
    wx.navigateTo({
      url: '../car_company/orderAdd/orderAdd'
    });
  },



  godetailforcarcompany: function (e) {
    console.log(e)
    wx.navigateTo({
      url: '../car_company/orderDetail/orderDetail?IDD=' + e.currentTarget.id,
    })
  },

  getMeetingList: function () {
    var that = this
    var userInfo = wx.getStorageSync('userInfo');
    console.log(userInfo)
    console.log(that.data.pageIndex)
    if (that.data.pageIndex != 1) {
      console.log('不是第一页，不刷新会议')
      return
    }
    that.setData({
      meetinglist: [],
    });
    wx.request({
      url: 'https://www.lanshuicar.com/Server/Meeting/MtHandler.ashx',
      data: {
        type: 3,
        id: userInfo.Id,
        // stime: '2018-01-01',
        STime: that.data.date,
      },
      method: 'GET',
      success: function (res) {
        console.log(res)
        if (res.statusCode == 404) {
          //接口加载失败
          console.log('加载接口错误');
          //隐藏Toast
          wx.hideToast();
          //显示错误信息
          that.showError('获取会议接口请求失败，请重试')
          return
        }
        var data = tool.getRegularJson(res.data);

        // if (that.data.list.length == 0) {
        //   that.setData({
        //     noData: true
        //   });
        //   console.log('###1')
        // } else {
        //   that.setData({
        //     noData: false
        //   });
        //   console.log('###2')
        // }

        if (data.data.length > 0) {
          that.setData({
            noMoreData: false
          });
          if (data.data.length == 0 && that.data.list.length == 0) {
            that.setData({
              noData: true
            });
            console.log('###1')
          } else {
            that.setData({
              noData: false
            });
            console.log('###2')
          }


          // that.setData({
          that.data.meetinglist = that.data.meetinglist.concat(data.data)
          // });
          console.log(that.data.meetinglist)
        } else {

        }

        if (that.data.meetinglist.length > 0) {
          that.setData({
            havemeet: true,
          })
          that.changetimeformeet()
        }
      },
      complete: function (res) {
        console.log(res)
        console.log('#1')
        setTimeout(function () {
          wx.hideToast();
        }, 400)
      }
    })
  },

  changetimeformeet: function () {
    var that = this
    console.log('执行了日期截断操作')
    for (var i = 0; i < that.data.meetinglist.length; i++) {
      // that.data.meetinglist[i].KSRQ = that.data.meetinglist[i].KSRQ.substring(0, 16)
      var sDate = that.data.meetinglist[i].KSRQ.substring(0, 10)
      var sTime = that.data.meetinglist[i].KSSJ.substring(11, 16)
      that.data.meetinglist[i].KSRQ = sDate + ' ' + sTime

      console.log(that.data.meetinglist[i].KSRQ)
    }
    that.setData({
      meetinglist: that.data.meetinglist,
    })
  },

  showError: function (msg) {
    var that = this;
    that.setData({
      formError: true,
      errorMessage: msg
    });

    setTimeout(function () {
      that.setData({
        formError: false,
        errorMessage: '未知错误'
      });
    }, 2000);
  },

  radioChange: function (e) {
    console.log(e)
    console.log('radio发生change事件，携带value值为：', e.detail.value)
  },

  goQROrder: function () {
    var that = this
    wx.navigateTo({
      url: '../passengers/passengerDe?IDD=' + that.data.QROrderIDD,
    })
  }
})

function loadListData(that, pageIndex) {
  that.setData({
    noData: false
  });
  var userInfo = wx.getStorageSync('userInfo');
  console.log(userInfo)
  wx.setStorageSync('newuserInfo', userInfo)
  console.log(pageIndex)
  if (pageIndex == 1) {
    that.setData({
      list: []
    });
  }
  setTimeout(function () {
    wx.showToast({
      title: '正在加载...',
      icon: 'loading',
      duration: 10000
    })
  }, 400)
  var userType1 = wx.getStorageSync('userType');
  that.setData({
    userType: userType1
  });

  console.log(that.data.enddate)
  console.log(that.data.date)

  switch (userType1) {
    case '1':
      //车公司首页
      wx.request({
        url: 'https://www.lanshuicar.com/Server/CarCompany/CarCompFindOrders.ashx',
        data: {
          ID: userInfo.ZID,
          ic: 'time',
          PageIndex: pageIndex,
          PageSize: 20,
          firstday: that.data.date,
          lastday: that.data.enddate,
          Compid: that.data.traAgencyIndex == -1 ? '' : that.data.traAgencyArray[that.data.traAgencyIndex].AgencyZID,
          Status: that.data.traStatusIndex == -1 ? '' : that.data.traStatusArray[that.data.traStatusIndex].id,
          comp: that.data.inputVal
        },
        method: 'GET',
        success: function (res) {
          console.log(res)
          if (res.statusCode == 404) {
            //接口加载失败
            console.log('加载接口错误');
            //隐藏Toast
            setTimeout(function () {
              wx.hideToast();
            }, 400)
            //显示错误信息
            that.showError('接口请求失败，请重试')
            that.setData({
              loadError: true
            });
            return
          }


          var data = tool.getRegularJson(res.data);
          console.log(data)
          setTimeout(function () {
            wx.hideToast();
          }, 400)
          // wx.hideLoading()

          if (data.code == '0') {
            console.log('接口调用成功，code=0')

            if (data.data.length > 0) {
              console.log('有订单数据')
              //数据存入list中备用
              that.data.list = that.data.list.concat(data.data)
              //执行修改日期的操作
              setdate(that)
              console.log(that.data.list)
            } else {
              console.log('没有有订单数据')
              //当pageindex不等于1时，不显示无订单模块
              if (pageIndex == 1) {
                that.setData({
                  noData: true
                });
              } else {
                that.data.pageIndex = pageIndex - 1
              }
            }
          } else {
            //返回code不为0，说明有错误
            console.log('接口调用成功，但是操作有误，返回值不为0，打印错误信息')
            that.setData({
              loadError: true
            });
            that.showError(data.msg)
          }
          //停止下拉刷新动画
          wx.stopPullDownRefresh();
          //刷新之后自动重新加载旅行社信息
          loadTraAgencyName(that);
        },
        fail: function () {
          //接口加载失败
          console.log('加载接口错误');
          //隐藏Toast
          setTimeout(function () {
            wx.hideToast();
          }, 400)
          //显示错误信息
          that.showError('接口请求失败，请重试')
          that.setData({
            loadError: true
          });
        }
      })
      break;

    //旅行社首页
    case '2':
      wx.request({
        url: 'https://www.lanshuicar.com/Server/AgencyServer/OrderListHandler.ashx',
        data: {
          ID: userInfo.ID,
          PageIndex: pageIndex,
          PageSize: 20,
          STime: that.data.date == '' ? '2018-01-01' : that.data.date,
          ETime: that.data.enddate,
          Condition: that.data.inputVal
        },
        method: 'GET',
        success: function (res) {
          if (res.statusCode == 404) {
            //接口加载失败
            console.log('加载接口错误');
            //隐藏Toast
            setTimeout(function () {
              wx.hideToast();
            }, 400)
            //显示错误信息
            that.showError('接口请求失败，请重试')
            that.setData({
              loadError: true
            });
            return
          }
          var data = tool.getRegularJson(res.data);
          console.log(data)
          setTimeout(function () {
            wx.hideToast();
          }, 400)

          if (data.code == '0') {
            console.log('接口调用成功，code=0')
            console.log(that.data.noData)
            if (data.data.length > 0) {
              console.log('有订单数据')
              //数据存入list中备用
              // that.setData({
              //   list: that.data.list.concat(data.data)
              // })
              that.data.list = that.data.list.concat(data.data)
              //执行修改日期的操作
              setdate(that)
              console.log(that.data.list)
            } else {
              console.log('没有有订单数据')
              //当pageindex不等于1时，不显示无订单模块
              if (pageIndex == 1) {
                that.setData({
                  noData: true
                });
              } else {
                that.data.pageIndex = pageIndex - 1
              }
            }
          } else {
            //返回code不为0，说明有错误
            console.log('接口调用成功，但是操作有误，返回值不为0，打印错误信息')
            that.setData({
              loadError: true
            });
            that.showError(data.msg)
          }
          //停止下拉刷新动画
          wx.stopPullDownRefresh();
          // wx.hideToast();
          // var data = tool.getRegularJson(res.data);

          // if (data.data.length > 0) {
          //   that.setData({
          //     list: that.data.list.concat(data.data),
          //     noMoreData: false,
          //     noData: false
          //   });
          //   setdate(that);
          //   console.log(that.data.list)
          // } else {
          //   that.setData({
          //     noMoreData: true
          //   });
          // }

          // if (that.data.list.length == 0) {
          //   that.setData({
          //     noData: true
          //   });
          // }

          // that.setData({
          //   loadError: false
          // });
          // wx.stopPullDownRefresh();
        },
        fail: function () {
          //接口加载失败
          console.log('加载接口错误');
          //隐藏Toast
          setTimeout(function () {
            wx.hideToast();
          }, 400)
          //显示错误信息
          that.showError('接口请求失败，请重试')
          that.setData({
            loadError: true
          });
        }
      })
      break;

    //司机首页
    case '3':
      var mData = {
        ID: userInfo.Id,
        PageIndex: pageIndex,
        PageSize: 10,
        fstday: that.data.date,
        lstday: that.data.enddate,
        statu: that.data.payStatusIndex == -1 ? '' : that.data.payArray[that.data.payStatusIndex].id,
        search: that.data.inputVal
      };
      console.log('getgo')
      console.log(mData)
      wx.request({
        url: 'https://www.lanshuicar.com/Server/DriverPerson/DriverFindOrders.ashx',
        data: mData,
        method: 'GET',
        success: function (res) {
          if (res.statusCode == 404) {
            //接口加载失败
            console.log('加载接口错误');
            //隐藏Toast
            setTimeout(function () {
              wx.hideToast();
            }, 400)
            //显示错误信息
            that.showError('接口请求失败，请重试')
            that.setData({
              loadError: true
            });
            return
          }
          var data = tool.getRegularJson(res.data);
          console.log(data)
          setTimeout(function () {
            wx.hideToast();
          }, 400)

          if (data.code == '0') {
            console.log('接口调用成功，code=0')
            if (data.data.length > 0) {
              console.log('有订单数据')
              //数据存入list中备用
              that.data.list = that.data.list.concat(data.data)
              //执行修改日期的操作
              setdate(that)
              console.log(that.data.list)
            } else {
              console.log('没有有订单数据')
              //当pageindex不等于1时，不显示无订单模块
              if (pageIndex == 1) {
                that.setData({
                  noData: true
                });
              } else {
                that.data.pageIndex = pageIndex - 1
              }
            }
          } else {
            //返回code不为0，说明有错误
            console.log('接口调用成功，但是操作有误，返回值不为0，打印错误信息')
            that.setData({
              loadError: true
            });
            that.showError(data.msg)
          }
          //停止下拉刷新动画
          wx.stopPullDownRefresh();
          // 获取会议列表
          if (!that.data.notloadmeeting) {
            console.log('加载了会议')
            that.getMeetingList()
          } else {
            console.log('没有加载会议')
            that.data.notloadmeeting = false
          }
        },
        fail: function () {
          //接口加载失败
          console.log('加载接口错误');
          //隐藏Toast
          setTimeout(function () {
            wx.hideToast();
          }, 400)
          //显示错误信息
          that.showError('接口请求失败，请重试')
          that.setData({
            loadError: true
          });
        }
      })
      break;

    //导游首页
    case '4':
      console.log(that.data.date)
      console.log(that.data.payStatusIndex)
      if (that.data.payStatusIndex != -1) {
        console.log(that.data.payArray[that.data.payStatusIndex])
        console.log(that.data.payArray[that.data.payStatusIndex].id)
      }
      wx.request({
        url: 'https://www.lanshuicar.com/Server/Guiders/GuidersHandler.ashx',
        data: {
          gid: userInfo.Id,
          PageIndex: pageIndex,
          PageSize: 20,
          STime: that.data.date,
          ETime: that.data.enddate,
          GTradeStatus: that.data.payStatusIndex == -1 ? '' : that.data.payArray[that.data.payStatusIndex].id,
          Condition: that.data.inputVal
        },
        method: 'GET',
        success: function (res) {
          if (res.statusCode == 404) {
            //接口加载失败
            console.log('加载接口错误');
            //隐藏Toast
            setTimeout(function () {
              wx.hideToast();
            }, 400)
            //显示错误信息
            that.showError('接口请求失败，请重试')
            that.setData({
              loadError: true
            });
            return
          }
          var data = tool.getRegularJson(res.data);
          console.log(data)
          setTimeout(function () {
            wx.hideToast();
          }, 400)

          if (data.code == '0') {
            console.log('接口调用成功，code=0')
            if (data.data.length > 0) {
              console.log('有订单数据')
              //数据存入list中备用
              that.data.list = that.data.list.concat(data.data)
              //执行修改日期的操作
              setdate(that)
              console.log(that.data.list)
            } else {
              console.log('没有有订单数据')
              //当pageindex不等于1时，不显示无订单模块
              if (pageIndex == 1) {
                that.setData({
                  noData: true
                });
              } else {
                that.data.pageIndex = pageIndex - 1
              }
            }
          } else {
            //返回code不为0，说明有错误
            console.log('接口调用成功，但是操作有误，返回值不为0，打印错误信息')
            that.setData({
              loadError: true
            });
            that.showError(data.msg)
          }
          //停止下拉刷新动画
          wx.stopPullDownRefresh();


          setTimeout(function () {
            wx.hideToast();
          }, 400)
          console.log(res)
        },
        fail: function () {
          //接口加载失败
          console.log('加载接口错误');
          //隐藏Toast
          setTimeout(function () {
            wx.hideToast();
          }, 400)
          //显示错误信息
          that.showError('接口请求失败，请重试')
          that.setData({
            loadError: true
          });
        }
      })
      break;

    //乘客首页
    case '5':
      wx.request({
        url: 'https://www.lanshuicar.com/Server/CustS/CustHandler.ashx',
        data: {
          cId: userInfo.Id,
          PageIndex: pageIndex,
          PageSize: 20,
          fstday: that.data.date,
        },
        method: 'GET',
        success: function (res) {
          if (res.statusCode == 404) {
            //接口加载失败
            console.log('加载接口错误');
            //隐藏Toast
            setTimeout(function () {
              wx.hideToast();
            }, 400)
            //显示错误信息
            that.showError('接口请求失败，请重试')
            that.setData({
              loadError: true
            });
            return
          }
          var data = tool.getRegularJson(res.data);
          console.log(data)
          setTimeout(function () {
            wx.hideToast();
          }, 400)

          if (data.code == '0') {
            console.log('接口调用成功，code=0')

            if (data.data.length > 0) {
              console.log('有订单数据')
              //数据存入list中备用
              that.data.list = that.data.list.concat(data.data)
              //执行修改日期的操作
              setdate(that)
              console.log(that.data.list)
            } else {
              console.log('没有有订单数据')
              //当pageindex不等于1时，不显示无订单模块
              if (pageIndex == 1) {
                that.setData({
                  noData: true
                });
              } else {
                that.data.pageIndex = pageIndex - 1
              }
            }
          } else {
            //返回code不为0，说明有错误
            console.log('接口调用成功，但是操作有误，返回值不为0，打印错误信息')
            that.setData({
              loadError: true
            });
            that.showError(data.msg)
          }
          //停止下拉刷新动画
          wx.stopPullDownRefresh();
        },
        fail: function () {
          //接口加载失败
          console.log('加载接口错误');
          //隐藏Toast
          setTimeout(function () {
            wx.hideToast();
          }, 400)
          //显示错误信息
          that.showError('接口请求失败，请重试')
          that.setData({
            loadError: true
          });
        },
        complete: function () {

        }
      })
      break;
  }

}

//数组去重
function uniqueList(array, that) {
  console.log('执行了去重操作')
  var r = [];
  for (var i = 0, l = array.length; i < l; i++) {
    for (var j = i + 1; j < l; j++)
      //关键在这里
      if (JSON.stringify(array[i].IDD) == JSON.stringify(array[j].IDD)) j = ++i;
    r.push(array[i]);
  }
  console.log(r)
  that.setData({
    list: r
  })
}

//日期分割
function setdate(that) {
  var list = that.data.list
  for (var i = 0; i < list.length; i++) {
    var date = list[i].UseCarStartTime
    date = date.substring(0, 10)
    list[i].UseCarStartTime = date
  }
  // that.setData({
  //   list: list
  // })

  uniqueList(list, that)
}

function showLoginModal(msg) {
  wx.showModal({
    content: msg,
    showCancel: false,
    success: function (res) {
      if (res.confirm) {
        wx.navigateTo({
          url: '/pages/login/login',
          success: function (res) {
            // success
          },
          fail: function () {
            // fail
          },
          complete: function () {
            // complete
          }
        })
      }
    }
  });
}

// function doUpLoadLocation(that) {
//   setInterval(function () {
//     console.log("开始上传位置")
//     appInstance.getLocation();
//   }, 10000)

// }

function login(that, appInstance) {
  //在App打开时，从存储中取出username和password，并执行登录方法，登录成功，就将全局变量中的hasLogin置为true，否则为false
  var username = wx.getStorageSync('username');
  var password = wx.getStorageSync('password');
  console.log('app.js', 'login start');
  console.log('app.js', username);
  console.log('app.js', password);
  if (username) {
    that.setData({
      firstLogin: false,
      isLogin: true,
      loginError: false
    });

    wx.request({
      url: 'https://www.lanshuicar.com/Server/LoginAPI.ashx',
      data: {
        Tel: username,
        password: password
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        // success
        // wx.hideToast();
        console.log('app.js', res);
        var code = res.data.code;
        if (code == 0) {
          console.log('app.js', 'login success');
          appInstance.globalData.hasLogin = true;

          var json = res.data.data[0];
          wx.setStorageSync('userInfo', json);

          that.setData({
            firstLogin: false,
            isLogin: false,
            loginError: false
          });
          that.loadlist()
          // loadListData(that, 1);

          //如果位置信息为打开状态，需要开始获取定位
          

          //登录成功后自动加载旅行社信息
          loadTraAgencyName(that);
        } else {
          console.log('app.js', 'login error');
          appInstance.globalData.hasLogin = false;

          that.setData({
            firstLogin: false,
            isLogin: false,
            loginError: true
          });
        }
      },
      fail: function () {
        // fail
        console.log('app.js', 'login error');
        appInstance.globalData.hasLogin = false;

        that.setData({
          firstLogin: false,
          isLogin: false,
          loginError: true
        });

        appInstance.stopLocationListener();
      },
      complete: function () {

      }
    })
  } else {
    console.log('app.js', 'login error');
    appInstance.globalData.hasLogin = false;

    that.setData({
      firstLogin: true,
      isLogin: false,
      loginError: false
    });

    wx.navigateTo({
      url: '../login/login',
    })
  }
}

function loadTraAgencyName(that) {
  var userInfo = wx.getStorageSync('userInfo');
  var userType = wx.getStorageSync('userType');

  wx.request({
    url: 'https://www.lanshuicar.com/Server/GetOrdersAgencyCarComList.ashx',
    data: {
      ID: userInfo.ZID,
      UType: userType,
      Type: 2
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    success: function (res) {
      // success
      var code = res.data.code;
      console.log(res.data.data)
      if (code == 0) {
        that.setData({
          traAgencyArray: res.data.data
        });
      }
    },
    fail: function () {
      // fail
    },
    complete: function () {
      // complete
    }
  });
}

function getlocate(that) {
  time : setInterval(function () {

    //var that = this;
    var countDownNum = that.data.countDownNum;
    //每隔一秒countDownNum就减一，实现同步
    countDownNum--;
    //然后把countDownNum存进data，好让用户知道时间在倒计着
    that.setData({
      countDownNum: countDownNum
    })
    //在倒计时还未到0时，这中间可以做其他的事情，按项目需求来
    if (countDownNum == 0) {
      //这里特别要注意，计时器是始终一直在走的，如果你的时间为0，那么就要关掉定时器！不然相当耗性能
      //因为timer是存在data里面的，所以在关掉时，也要在data里取出后再关闭
      clearInterval(that.data.timer);
      //关闭定时器之后，可作其他处理codes go here
    }
    console.log("开始上传位置")
    console.log(getApp().globalData.isUpLoadLocation)

    if (!getApp().globalData.isUpLoadLocation){
      console.log("返回了")
      return
    }

    var userType = wx.getStorageSync('userType');
    if (userType == 1 || userType == 2) {
      console.log('车公司，旅行社不获取位置')
      return
    }
    var longitude = ''
    var latitude = ''
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res)
        longitude = res.longitude
        latitude = res.latitude
        console.log('腾讯经纬度')
        console.log(longitude, latitude)
        decoding(longitude, latitude)
      }, fail(res) {
        wx.showToast({
          title: '您尚未开启定位服务或未授权定位权限',
          icon: 'none'
        })
        console.log(res)
      }
    })
  }, 1000)
}

//将腾讯坐标转化为百度坐标
function decoding(longitude, latitude) {
  if (!latitude) {
    return
  }
  if (!longitude) {
    return
  }
  var baidulongitude = ''
  var baidulatitude = ''
  var userType = wx.getStorageSync('userType');
  var coordinate = []
  wx.request({
    url: 'https://www.lanshuicar.com/Server/GpsDeal.ashx',
    data: {
      jdu: longitude,
      wdu: latitude
    },
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    success: function (res) {
      // success
      console.log(res)
      var data = tool.getRegularJson(res.data);
      var code = data.code;
      if (code == 0) {
        coordinate = data.data[0]
        baidulongitude = coordinate.x
        baidulatitude = coordinate.y
        if (baidulongitude == '4.9E-324' || baidulatitude == '4.9E-324') {
          return
        } else {
          SaveCoordinate(baidulongitude, baidulatitude)
          console.log('百度坐标')
          console.log(baidulongitude, baidulatitude)
        }
      }
    },
    fail: function (res) {
      console.log(res)
      // fail
    },
    complete: function (res) {
      console.log(res)
      // complete
    }
  });
}


function SaveCoordinate(blongitude, blatitude) {
  var userInfo = wx.getStorageSync('userInfo')
  var userType = wx.getStorageSync('userType')
  var tel = ''
  if (userType == 3 || userType == 4) {
    tel = userInfo.sTel
  } else if (userType == 5) {
    tel = userInfo.cTel
  }
  wx.request({
    url: 'https://www.lanshuicar.com/Server/InsertGPS.ashx',
    data: {
      phone: tel,
      jdu: blongitude,
      wdu: blatitude
    },
    method: 'GET',
    success: function (res) {
      // success
      console.log(res)
      var data = tool.getRegularJson(res.data);
      var code = data.code;
      if (code == 0) {
        console.log('保存位置成功')
      }
    },
    fail: function (res) {
      console.log(res)
      // fail
    }
  })
}

function getlogincode(that) {
  console.log('调用')
  wx.login({
    success: function (res) {
      var code = res.code
      testgetopenid(code)
      // getNeededUserInfo(that,code)
    }
  })
}

function testgetopenid(code) {
  var appid = 'wx584bcf68b02e7b27'; //填写微信小程序appid
  var secret = '5330c4a075c02e5815aa8bee144d8f3e'; //填写微信小程序secret

  //调用request请求api转换登录凭证
  wx.request({
    url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&grant_type=authorization_code&js_code=' + code,
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {
      console.log(res)
      console.log(res.data) //获取openid
    }
  })
}

function gopush(idd) {
  var userInfo = wx.getStorageSync('userInfo')
  var usertype = userInfo.USerType
  console.log(userInfo, usertype)

  if (userInfo) {
    console.log('user')
    if (userInfo.USerType == 1) {
      console.log('go1')
      wx.navigateTo({
        url: '../car_company/orderDetail/orderDetail?IDD=' + idd,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
    if (userInfo.USerType == 2) {
      console.log('go2')
      wx.navigateTo({
        url: '../travelAgency/travelAgencyDetail?IDD=' + idd,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
    if (userInfo.USerType == 3) {
      console.log('go3')
      wx.navigateTo({
        url: '../driver/order_detail/order_detail?IDD=' + idd,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
    if (userInfo.USerType == 4) {
      console.log('go4')
      wx.navigateTo({
        url: '../guiders/guiderdetail?IDD=' + idd,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
    if (usertype == '5') {
      console.log('go5')
      wx.navigateTo({
        url: '../passengers/passengerDe?IDD=' + idd,
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }

  }

  else {
    console.log('nologin')
  }

}
// function getEncData() {
//   　　　　wx.getUserInfo({
//     　　　　　　withCredentials: true,
//     　　　　　　success: function (res) {
//       　　　　　　　　that.getNeededUserInfo(code, res.encryptedData, res.encryptedData);
//     　　　　　　}
//   　　　　})
// 　　}

// function getNeededUserInfo(code, enc, iv) {
//   　　　　wx.request({
//     　　　　　　url: 'https://my.com/login',
//     　　　　　　method: 'POST',
//     　　　　　　data: {
//       　　　　　　　　code: code,
//       　　　　　　　　encryptedData: enc,
//       　　　　　　　　iv: iv
//     　　　　　　},
//     　　　　　　success: function (res) {
//               console.log(res)
//       　　　　　　　　// 可以返回前端需要的用户信息（包括unionid、openid、user_id等）
//     　　　　　　}
//   　　　　})
// 　　}


